<?php
// +----------------------------------------------------------------------
// | Description: 用户
// +----------------------------------------------------------------------
// | Author: linchuangbin <linchuangbin@honraytech.com>
// +----------------------------------------------------------------------

namespace app\admin\model;

use think\Db;
use app\admin\model\Common;
use com\verify\HonrayVerify;

class Tondun extends Common
{

    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如微信模块用weixin作为数据表前缀
     */
    protected $name = 'td_preloan_report';     //征信记录表
    protected $createTime = 'create_time';
    protected $updateTime = false;
    protected $autoWriteTimestamp = true;
    protected $insert = [
        'status' => 1,
    ];
    /*定义方法 如果出现该字段则直接显示中文*/
    public function getisTestAttr($value)
    {
        $data = ['0'=>"线上",'1'=>"测试"];
        return '接口调用-'.$data[$value];
    }
    public function getstatusAttr($value)
    {
        $data = ['0'=>"还未生成",'1'=>"已生成"];
        return $data[$value];
    }
    /**
     * 获取用户所属所有用户组
     * @param  array   $param  [description]
     */
    public function groups()
    {
        return $this->belongsToMany('group', '__ADMIN_ACCESS__', 'group_id', 'user_id');
    }

    /**
     * [getDataList 列表]
     * @AuthorHTL
     * @DateTime  2017-02-10T22:19:57+0800
     * @param     [string]                   $keywords [关键字]
     * @param     [number]                   $page     [当前页数]
     * @param     [number]                   $limit    [t每页数量]
     * @return    [array]                             [description]
     */
    public function getDataList($keywords, $page=1, $limit=15)
    {
        $map = array();
        if ($keywords) {
            $map['b.name'] = ['like', '%'.trim($keywords).'%'];
        }

        $dataCount = $this->alias('a')
            ->join('qh_td_preloan_apply b','a.report_id = b.report_id','left')
            ->join('qh_user_info c','a.uid = c.uid','left')
            ->field('a.id,a.status,a.final_decision,a.apply_time,a.is_test,a.report_id,c.name')
            ->order('apply_time desc')
            ->where($map)
            ->count();

        $list = $this->alias('a')
            ->join('qh_td_preloan_apply b','a.report_id = b.report_id','left')
            ->join('qh_user_info c','a.uid = c.uid','left')
            ->field('a.id,a.status,a.final_decision,a.apply_time,a.is_test,a.report_id,c.name')
            ->order('apply_time desc')
            ->where($map)
            ->page($page, $limit)
            ->select();

        $list = modelo2array($list);
        $data['list'] = $list;
        $data['dataCount'] = $dataCount;
        foreach($data['list'] as &$v){
            $v['apply_time']=date("Y-m-d H:i:s", $v['apply_time']);
        }
        return $data;
    }

    /**
     * [getDataById 根据主键获取详情]
     * @linchuangbin
     * @DateTime 2017-02-10T21:16:34+0800
     * 
     * @param string $id
     *            [主键]
     * @return [array]
     */
    public function getDataById($id = '')
    {
        $is_set = $this->where(['id'=>$id])->find();
        $report_id = $is_set['report_id'];
        if(!$is_set){
           $this->error = '报告id不存在!';
           return false;
        }
        $param['label']   = $report_id;
        $param['channel'] = config('operator_channel');
        //将风险报告分类
        $fenlei=array();
        /*在提交的信系表里 根据订单id查用户信息*/
        $preson_info = $this->alias('a')->field("b.name,b.phone mobile")->join('user_info b','b.uid = a.uid','LEFT')->where("a.report_id",$report_id)->find();
        $preson_info['report_id'] = $report_id;
        $preson_info['final_decision'] = $is_set['final_decision'];
        $preson_info['final_level'] = $is_set['final_level'];
        $preson_info['status_code'] = $is_set['status_code'];
        $preson_info['return_message'] = $is_set['return_message'];
        $result = preloan_report($param);
        if($result['code'] == 200)
        {
           $preson_info['water_info'] = $result['data']['JsonData'];
        }else{
            $preson_info['water_info'] = [];
        }
        return $preson_info;

        /*$data = $this
                ->alias('a')
                ->join('qh_td_preloan_apply b','a.report_id = b.report_id')
                ->where('a.id', $id)
                ->field('a.risk_items,a.address_detect,b.name,b.mobile,a.status as state,a.report_id')
                ->find();
        # 报告未生成的刷新一次
        if($data['state'] == 0){
            $refresh = model('admin/Credit')->refresh($data['report_id']);
        }
        $report = json_decode($data['risk_items'], true);
// dump('getDataById');
// dump($data);
// dump($data['risk_items']);
// die;
        try {
            // dump($report);
            // die;
            if(!empty($report)){
                foreach ($report as $k => $v) {
                    if ($v['risk_level'] == "low") {
                        $lv = "低";
                    } elseif ($v['risk_level'] == "medium") {
                        $lv = "中";
                    } elseif ($v['risk_level'] == "high") {
                        $lv = "高";
                    }
                    
                    $list['risk'] = $lv;
                    $list['group'] = $v['group'];
                    $list['item_name'] = $v['item_name'];
                    $list['data'] = [];
                    
                    if ($v['item_detail']['high_risk_areas']) {
                        $list['detail'] = $v['item_detail']['high_risk_areas'];
                    }
                    
                    if ($v['item_detail']['frequency_detail_list']) {
                        foreach ($v['item_detail']['frequency_detail_list'] as $kk => $vv) {
                            $idcard[] = $vv['detail'];
                            $data1[] = $vv['data'];
                        }
                        $list['detail'] = $idcard;
                    }
                    if ($v['item_detail']['platform_detail']) {
                        $list['detail'] = $v['item_detail']['platform_detail'];
                    }
                    
                    $arr[] = $list;
                }
            }

            if(!empty($report)){
                foreach ($arr as $kl => $vl) {
                    if ($vl['item_name'] == '地址匹配') {
                        unset($arr[$kl]);
                    }
                    if($vl['group'] == '客户行为检测'){
                        $arr[$kl]['data']  = $data1;
                    }
                }
            }
            
            $msg = json_decode($data['address_detect'],true);
            $row['mobile_address'] = $msg['mobile_address'];
            $row['id_card_address'] = $msg['id_card_address'];
            $row['name'] = $data['name'];
            $row['mobile'] = $data['mobile'];
            $row['risk_items'] = $arr;
            return $row;
        } catch(\Exception $e) {
            $this->error = '数据有误';
            return false;
        }*/

    }
    
    
    /**
     * 创建用户
     * @param  array   $param  [description]
     */
    public function createData($param)
    {
        if (empty($param['groups'])) {
            $this->error = '请至少勾选一个用户组';
            return false;
        }

        // 验证
        $validate = validate($this->name);
        if (!$validate->check($param)) {
            $this->error = $validate->getError();
            return false;
        }

        $this->startTrans();
        try {
            $param['password'] = user_md5($param['password']);
            $this->data($param)->allowField(true)->save();

            foreach ($param['groups'] as $k => $v) {
                $userGroup['user_id'] = $this->id;
                $userGroup['group_id'] = $v;
                $userGroups[] = $userGroup;
            }
            Db::name('admin_access')->insertAll($userGroups);

            $this->commit();
            return true;
        } catch(\Exception $e) {
            $this->rollback();
            $this->error = '添加失败';
            return false;
        }
    }

    /**
     * 通过id修改用户
     * @param  array   $param  [description]
     */
    public function updateDataById($param, $id)
    {
        // 不能操作超级管理员
        if ($id == 1) {
            $this->error = '非法操作';
            return false;
        }
        $checkData = $this->get($id);
        if (!$checkData) {
            $this->error = '暂无此数据';
            return false;
        }
        $validate = validate($this->name);
        if (!$validate->check($param)) {
            $this->error = $validate->getError();
            return false;
        }
        $re=$this->allowField(true)->save($param, ['uid' => $id]);
        $arr=array();
        $arr['name']=$param['name'];
        $arr['age']=$param['age'];
        $arr['sex']=$param['sex'];
        $arr['qq']=$param['qq'];
        $arr['phone']=$param['phone'];
        $arr['zhima']=$param['zhima'];
        $arr['province']=$param['province'];
        $arr['update_time']=date('Y-m-d H:i:s',time());;
        $re1=Db::name('user_info')->where('uid',$id)->update($arr);
        if($re || $re1){
            return true;
        }else{
            $this->error = '编辑失败';
            return false;
        }
    }

    /**
     * [login 登录]
     * @AuthorHTL
     * @DateTime  2017-02-10T22:37:49+0800
     * @param     [string]                   $u_username [账号]
     * @param     [string]                   $u_pwd      [密码]
     * @param     [string]                   $verifyCode [验证码]
     * @param     Boolean                  	 $isRemember [是否记住密码]
     * @param     Boolean                    $type       [是否重复登录]
     * @return    [type]                               [description]
     */
    public function login($username, $password, $verifyCode = '', $isRemember = false, $type = false)
    {
        if (!$username) {
            $this->error = '帐号不能为空';
            return false;
        }
        if (!$password){
            $this->error = '密码不能为空';
            return false;
        }
        if (config('IDENTIFYING_CODE') && !$type) {
            if (!$verifyCode) {
                $this->error = '验证码不能为空';
                return false;
            }
            $captcha = new HonrayVerify(config('captcha'));
            if (!$captcha->check($verifyCode)) {
                $this->error = '验证码错误';
                return false;
            }
        }

        $map['username'] = $username;
        $userInfo = $this->where($map)->find();
        if (!$userInfo) {
            $this->error = '帐号不存在';
            return false;
        }
        if (user_md5($password) !== $userInfo['password']) {
            $this->error = '密码错误';
            return false;
        }
        if ($userInfo['status'] === 0) {
            $this->error = '帐号已被禁用';
            return false;
        }

        // return $userInfo;


        /*以下先关闭*/

        // 获取菜单和权限
        $dataList = $this->getMenuAndRule($userInfo['id']);

        if (!$dataList['menusList']) {
            $this->error = '没有权限';
            return false;
        }

        if ($isRemember || $type) {
            $secret['username'] = $username;
            $secret['password'] = $password;
            $data['rememberKey'] = encrypt($secret);
        }

        // 保存缓存
        session_start();
        $info['userInfo'] = $userInfo;
        $info['sessionId'] = session_id();
        $authKey = user_md5($userInfo['username'].$userInfo['password'].$info['sessionId']);
        $info['_AUTH_LIST_'] = $dataList['rulesList'];
        $info['authKey'] = $authKey;
        cache('Auth_'.$authKey, null);
        cache('Auth_'.$authKey, $info, config('LOGIN_SESSION_VALID'));
        // 返回信息
        $data['authKey']		= $authKey;
        $data['sessionId']		= $info['sessionId'];
        $data['userInfo']		= $userInfo;
        $data['authList']		= $dataList['rulesList'];
        $data['menusList']		= $dataList['menusList'];
        return $data;
    }

    /**
     * 修改密码
     * @param  array   $param  [description]
     */
    public function setInfo($auth_key, $old_pwd, $new_pwd)
    {
        $cache = cache('Auth_'.$auth_key);
        if (!$cache) {
            $this->error = '请先进行登录';
            return false;
        }
        if (!$old_pwd) {
            $this->error = '请输入旧密码';
            return false;
        }
        if (!$new_pwd) {
            $this->error = '请输入新密码';
            return false;
        }
        if ($new_pwd == $old_pwd) {
            $this->error = '新旧密码不能一致';
            return false;
        }

        $userInfo = $cache['userInfo'];
        $password = $this->where('id', $userInfo['id'])->value('password');
        if (user_md5($old_pwd) != $password) {
            $this->error = '原密码错误';
            return false;
        }
        if (user_md5($new_pwd) == $password) {
            $this->error = '密码没改变';
            return false;
        }
        if ($this->where('id', $userInfo['id'])->setField('password', user_md5($new_pwd))) {
            $userInfo = $this->where('id', $userInfo['id'])->find();
            // 重新设置缓存
            session_start();
            $cache['userInfo'] = $userInfo;
            $cache['authKey'] = user_md5($userInfo['username'].$userInfo['password'].session_id());
            cache('Auth_'.$auth_key, null);
            cache('Auth_'.$cache['authKey'], $cache, config('LOGIN_SESSION_VALID'));
            return $cache['authKey'];//把auth_key传回给前端
        }

        $this->error = '修改失败';
        return false;
    }

    /**
     * 获取菜单和权限
     * @param  array   $param  [description]
     */
    protected function getMenuAndRule($u_id)
    {
        if ($u_id === 1) {
            $map['status'] = 1;
            $menusList = Db::name('admin_menu')->where($map)->order('sort asc')->select();
        } else {
            $groups = $this->get($u_id)->groups;
            $ruleIds = [];
            foreach($groups as $k => $v) {
                $ruleIds = array_unique(array_merge($ruleIds, explode(',', $v['rules'])));
            }

            $ruleMap['id'] = array('in', $ruleIds);
            $ruleMap['status'] = 1;
            // 重新设置ruleIds，除去部分已删除或禁用的权限。
            $rules =Db::name('admin_rule')->where($ruleMap)->select();
            foreach ($rules as $k => $v) {
                $ruleIds[] = $v['id'];
                $rules[$k]['name'] = strtolower($v['name']);
            }
            empty($ruleIds)&&$ruleIds = '';
            $menuMap['status'] = 1;
            $menuMap['rule_id'] = array('in',$ruleIds);
            $menusList = Db::name('admin_menu')->where($menuMap)->order('sort asc')->select();
        }
        if (!$menusList) {
            return null;
        }
        //处理菜单成树状
        $tree = new \com\Tree();
        $ret['menusList'] = $tree->list_to_tree($menusList, 'id', 'pid', 'child', 0, true, array('pid'));
        $ret['menusList'] = memuLevelClear($ret['menusList']);
        // 处理规则成树状
        $ret['rulesList'] = $tree->list_to_tree($rules, 'id', 'pid', 'child', 0, true, array('pid'));
        $ret['rulesList'] = rulesDeal($ret['rulesList']);

        return $ret;
    }
}